﻿using AVCUMPlatform.BLL.Interface;
using AVCUMPlatform.BLL;
using AVCUMPlatform.Entities;
using AVCUMPlatform.Models;
using Microsoft.AspNetCore.Mvc;
using AVCUMPlatform.HelperLibrary;

namespace AVCUMPlatform.Controllers
{
    /// <summary>
    /// 来源接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class SourceController : ControllerBase
    {
        private ISourceBLL _sourceBll = BLLContainer.Resolve<ISourceBLL>();
        private IMessageTypesBLL _messageTypesBll = BLLContainer.Resolve<IMessageTypesBLL>();
        private IClientInfoBLL _clientInfoBll = BLLContainer.Resolve<IClientInfoBLL>();
        private IMessageBLL _messageBll = BLLContainer.Resolve<IMessageBLL>();
        /// <summary>
        /// 分页查询消息
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="field">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetList(int page, int limit, string? field, string? order)
        {
            var list = _sourceBll.GetAll(); 
            if (!string.IsNullOrWhiteSpace(field) && field != "undefined")
            {
                if (!string.IsNullOrWhiteSpace(order) && order != "undefined")
                {
                    if (order == "desc")
                    {
                        if (field == "id")
                        {
                            list = list.OrderByDescending(x => x.Id).ToList();
                        }
                    }
                    else
                    {
                        if (field == "id")
                        {
                            list = list.OrderBy(x => x.Id).ToList();
                        }
                    }
                }
            }
            var count = list.Count();
            list = list.Skip((page - 1) * limit).Take(limit).ToList();
            var vmList = new List<SourceVM>();
            var msgTypes = _messageTypesBll.GetAll();
            var clientInfos = _clientInfoBll.GetAll();
            var messages = _messageBll.GetAll();
            foreach (var item in list)
            {
                var existmsgTypes = msgTypes.FirstOrDefault(x => x.Source == item.Id);
                var existclientInfos = clientInfos.FirstOrDefault(x => x.Source == item.Id);
                var existmessages = messages.FirstOrDefault(x => x.Source == item.Id);
                var vm = new SourceVM()
                {
                    Id = item.Id,
                    Code = item.Code,
                    Name = item.Name,
                    AK = item.AK,
                    SK = item.SK,
                    IsCanDelete = (existmsgTypes == null || existmsgTypes.Id <= 0) && (existclientInfos == null || existclientInfos.Id <= 0) && (existmessages == null || existmessages.Id <= 0) ? 1 : 2
                };
                vmList.Add(vm);
            }
            var obj = new { code = 0, count, data = vmList, msg = "" };
            return new JsonResult(obj);
        }

        /// <summary>
        /// 分页查询消息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ActionResult GetAll()
        {
            var list = _sourceBll.GetAll();
            var obj = new { code = 0, count = list.Count, data = list, msg = "" };
            return new JsonResult(obj);
        }
        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        [HttpPost]
        [NoNeedLogin]
        public ResultModel AddOrUpdate(Source source)
        {
            var ret = new ResultModel();
            if (source.Id > 0)
            {
                var existSource = _sourceBll.Get(source.Id);
                existSource.Name = source.Name;
                _sourceBll.Update(existSource);
            }
            else
            {
                var existSource = _sourceBll.GetAll().Where(x => x.Code == source.Code).ToList();
                if (existSource != null && existSource.Any())
                {
                    ret.code = -1;
                    ret.msg = "当前code已经存在";
                    return ret;
                }
                source.AK = Util.MD5Encrypt32(Util.CreateGUID(1));
                source.SK = Util.MD5Encrypt32(Util.CreateGUID(1));
                _sourceBll.Add(source);
            }
            ret.code = 1;
            return ret;
        }

        ///// <summary>
        ///// 新增或编辑(包含服务权限token认证)
        ///// </summary>
        ///// <param name="sourceReq"></param>
        ///// <returns></returns>
        //[HttpPost]
        //public ResultModel AddOrUpdate([FromBody] SourceReq sourceReq)
        //{
        //    var ret = new ResultModel();
        //    if (string.IsNullOrWhiteSpace(sourceReq.Code) || string.IsNullOrWhiteSpace(sourceReq.Name))
        //    {
        //        ret.code = -1;
        //        ret.msg = "无效参数";
        //        return ret;
        //    }
        //    var existSource = _sourceBll.GetAll().FirstOrDefault(x => x.Code == sourceReq.Code.Trim());
            
        //    if (existSource != null && existSource.Id > 0)
        //    {
        //        existSource.Name = sourceReq.Name.Trim();
        //        ret.code = _sourceBll.Update(existSource) ? 1 : -1;
        //    }
        //    else
        //    {
        //        var source = new Source()
        //        {
        //            Code = sourceReq.Code.Trim(),
        //            Name = sourceReq.Name.Trim(),
        //        };
        //        ret.code = _sourceBll.Add(source) ? 1 : -1;
        //    }
        //    ret.msg = ret.code == 1 ? "成功" : "失败";
        //    return ret;
        //}

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel Delete(int id)
        {
            var ret = new ResultModel();
            ret.code = _sourceBll.Delete(new List<int>() { id }) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        [NoNeedLogin]
        public ResultModel BatchDelete(string ids)
        {
            var ret = new ResultModel();
            var idList = ids.Split(',').Select(x => Convert.ToInt32(x)).ToList();
            ret.code = _sourceBll.Delete(idList) ? 1 : -1;
            if (ret.code == -1)
            {
                ret.msg = "删除失败";
            }
            return ret;
        }

    }
}
